package com.eight.cloud.gateway.filters;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eight.cloud.gateway.config.AuthExcludeProperties;
import com.eight.cloud.core.global.result.Result;
import com.eight.cloud.core.global.result.ResultCode;
import com.eight.cloud.gateway.utils.ServerHttpResponseUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

import static com.eight.cloud.core.global.constant.NumConstant.*;
import static com.eight.cloud.core.global.constant.StrConstant.*;

/**
 * 权限校验过滤器
 *
 * @ClassName: GlobalFilter
 * @Author: TXC
 * @Date: 2024-10-18 15:35
 **/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private AuthExcludeProperties authExcludeProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        String token = Optional.ofNullable(getAccessToken(request)).map(header -> header.get(ZERO)).orElse(null);
        ServerHttpResponse response = exchange.getResponse();
        try {
            if (StrUtil.isBlank(token)) {
                return ServerHttpResponseUtil.out(response, Result.fail(ResultCode.USER_NOT_LOGIN));
            }
        } catch (Exception e) {
            return ServerHttpResponseUtil.out(response, Result.fail(ResultCode.USER_ACCOUNT_EXPIRED));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * 排除路径
     *
     * @param path 路径
     * @return 是否排除
     * @author TXC
     */
    private boolean isExclude(String path) {
        for (String excludePath : authExcludeProperties.getExcludes()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取 AccessToken
     */
    public List<String> getAccessToken(ServerHttpRequest request) {
        List<String> accessToken = request.getHeaders().get(AUTHORIZATION);
        if (ObjectUtil.isEmpty(accessToken)) {
            accessToken = request.getHeaders().get(TOKEN);
        }
        return accessToken;
    }
}
